// pages/match/match.js
// const match = require('../../utils/match');
const group = require('../../utils/group');
var match = require('../../utils/match');
Page({
  tijiao() {
    var that = this;
    var matchid = this.data.matchid;
    var index = this.data.category;
    var userid = this.data.userid;
    var username = this.data.username;
    var time = new Date();//到达的时间
    var image = null;//提交的图片
    wx.chooseMedia({
      count: 1,
      success(res) {
        console.log(res.tempFiles)
        var po = res.tempFiles[0].tempFilePath.lastIndexOf(".")
        var ext = res.tempFiles[0].tempFilePath.slice(po)
        wx.cloud.uploadFile({
          cloudPath: matchid + index + userid + ext,
          filePath: res.tempFiles[0].tempFilePath,
          success(res) {
            console.log(res.fileID)
            image = res.fileID;
            that.setData({
              currentImage: image
            });
            var database = wx.cloud.database();
            database.collection("tb_item").add({
              data: {
                matchid: matchid,
                index: index,
                userid: userid,
                username: username,
                time: time,
                image: image
              }
            }).then((s) => {
              if (s) {
                wx.showToast({
                  title: '提交照片成功',
                });
                // 判断怎么完整整场比赛
                database.collection("tb_item").where({
                  matchid: that.data.matchid,
                  userid: that.data.userid
                }).get().then((b) => {
                  // 判断用户完成的当前比赛的分项数量是否等于比赛中的·场景数量
                  if (b.data.length == that.data.imageList.length) {
                    var matchid = that.data.matchid;
                    var matchname = that.data.matchname;
                    var userid = that.data.userid;
                    var username = that.data.username;
                    // 寻找当前用户的名次并更新到数据库
                    database.collection("tb_final").where({
                      matchid: matchid,
                      userid: userid
                    }).get().then((c) => {
                      var len = c.data.length;
                      var mingci = len + 1;
                      // 获取比赛的结束时间，
                      var endTime = new Date();
                      // 获取比赛的开始时间
                      database.collection("tb_match").where({
                        _id: matchid
                      }).get().then((d) => {
                        var beginTime = d.data[0].beginTime;
                        // 比赛的时间间距
                        var shijiancha = endTime.getTime() - beginTime.getTime();
                        var hours = Math.floor(shijiancha / (1000 * 60 * 60));
                        var min = Math.floor(shijiancha % (1000 * 60 * 60) / 60000);
                        var sec = Math.floor(shijiancha % 60000 / 1000);
                        var haoshi = hours + "小时" + min + "分钟" + sec + "秒钟";
                        database.collection("tb_final").add({
                          data: {
                            matchid: matchid,
                            matchname: matchname,
                            userid: userid,
                            username: username,
                            mingci: "第" + mingci + "名",
                            shijiancha: shijiancha,
                            haoshi: haoshi
                          }
                        }).then((e) => {
                          if (e) {
                            wx.showToast({
                              title: '您已经完成了比赛，获得第' + mingci + "名",
                            });
                            // 判断是不是整个小队最后完成的人
                            database.collection("tb_rudui").where({
                              userid: that.data.userid
                            }).get().then((g) => {
                              if (g.data.length == 0) return;
                              var groupid = g.data[0].groupid;
                              // 找到小队的人数
                              database.collection("tb_rudui").where({
                                groupid: groupid
                              }).get().then((h) => {
                                // 记录小队的人数
                                var renshu = h.data.length;
                                var groupname = h.data[0].groupname;
                                // 去寻找小队里边的人是不是都有最后的成绩
                                wx.cloud.callFunction({
                                  name: "get_group_final",//云函数的文件名称
                                  data: {
                                    groupid: groupid
                                  },
                                  success: res => {
                                    // 数一下小组中有多少人有成绩
                                    var data = res.result.list;
                                    var sum = 0;
                                    for (let i = 0; i < data.length; i++) {
                                      if (data[i].list.length > 0) sum = sum + 1;
                                    }
                                    // 判断有成绩的人是否等于小组的人数
                                    if (renshu == sum) {
                                      // 到小组成绩表里边去查询指定比赛的记录条数
                                      database.collection("tb_xiaozu_chengji").where({
                                        matchid: that.data.matchid
                                      }).get().then((x) => {
                                        var mingci = x.data.length + 1;
                                        var h = haoshi;
                                        var s = shijiancha;
                                        database.collection("tb_xiaozu_chengji").add({
                                          data: {
                                            matchid: matchid,
                                            matchname: matchname,
                                            groupid: groupid,
                                            groupname: groupname,
                                            mingci: mingci,
                                            shijiancha: s,
                                            haoshi: h
                                          }
                                        }).then((z) => {
                                          if (z) wx.showToast({
                                            title: '小组比赛完成' + mingci,
                                          });
                                        });
                                      });
                                    }
                                  },
                                  fail: err => {

                                  }
                                });
                              });
                            });
                          }
                        });
                      });
                    });
                  }
                });//提交照片这边，改了下
              } else {
                wx.showToast({
                  title: '提交照片失败，请重试',
                  icon: 'none'
                });
              }
            });
          },
          fail: (err) => {
            console.log(err);
            wx.showToast({
              title: '照片上传失败，请重试',
              icon: 'none'
            });
          }
        });
      },
      fail: (err) => {
        console.log(err);
        wx.showToast({
          title: '选择照片失败，请重试',
          icon: 'none'
        });
      }
    });
  },
  click: function (e) {
    this.setData({
      category: e.currentTarget.id + ""
    });

    var that = this;

    var database = wx.cloud.database();
    database.collection("tb_item").where({
      userid: that.data.userid,
      matchid: that.data.matchid,
      index: that.data.category + ""
    }).get().then((a) => {
      if (a.data.length > 0) {
        that.setData({
          isWeiwangcheng: false
        });
      } else {
        that.setData({
          isWeiwangcheng: true
        });
      }
    });
    //console.log("场景下标："+that.data.category);

    database.collection("tb_item").where({
      matchid: that.data.matchid,
      index: that.data.category + ""
    }).get().then((res) => {
      that.setData({
        xuanshou: res.data
      });
      for (let i = 0; i < that.data.xuanshou.length; i++) {
        // 获取第二个页面的时间
        var time = that.data.xuanshou[i].time;
        var d = time.toLocaleDateString().substring(0, 10);
        var t = time.toTimeString().substring(0, 8);
        var time = d + " " + t;
        that.data.xuanshou[i].time = time;
      }
      that.setData({
        xuanshou: that.data.xuanshou
      });
    });
  },
  dianji() {
    var k = this.data.category;
    var img = this.data.imageList[k]
    this.setData({
      dialogShow_match: true,
      currentImage: img
    });
  },
  /**
   * 页面的初始数据
   */
  data: {
    isWeiwangcheng: true,
    currentImage: null,
    username: null,
    userid: null,
    matchid: null,
    matchname: null,
    picnames: [],
    imageList: [],
    xuanshou: [],//老师那边写了两个
    matches: match.list,
    category: 0,
    id: null,
    dialogShow_match: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    wx.getStorage({
      key: "userid",
      success(res) {
        that.setData({
          userid: res.data
        });
        // 到数据库里面找到当前用户参加的比赛
        var database = wx.cloud.database();
        database.collection("tb_user").where({
          _id: that.data.userid
        }).get().then((r) => {
          if (r) {
            const { data } = r;
            if (data && data[0]) {
              that.setData({
                username: data[0].name
              });
            } else {
              // 处理data为undefined或data[0]不存在的情况
              console.log("没有获取到用户数据");
            }
          } else {
            // 处理r为undefined的情况
            console.log("数据库查询没有返回结果");
          }
        });
        // 调用云函数，实现多表联合查询
        wx.cloud.callFunction({
          name: "get_current_match",
          data: {
            userid: that.data.userid
          },
          success: res => {
            console.log("云函数返回的数据的条数：" + res.result.list.length);
            var data = res.result.list;
            for (let i = 0; i < data.length; i++) {
              var f1 = true;
              f1 = data[i].list1[0].hasOwnProperty("beginTime");

              if (!f1) continue;
              var f2 = true;
              for (let j = 0; j < data[i].list2.length; j++) {
                if (data[i].matchid == data[i].list2[j].matchid) {
                  f2 = false;
                  break;
                }
              }
              if (!f2) continue;
              console.log("符合条件的比赛下标:" + i);
              that.setData({
                matchid: data[i].matchid,
                matchname: data[i].matchname
              });

              break;
            }
            // 检查matchname是否为有效字符串
            if (that.data.matchname) {
              wx.setNavigationBarTitle({
                title: that.data.matchname
              });
            } else {
              // 如果matchname为null或undefined，设置默认标题
              wx.setNavigationBarTitle({
                title: "正在比赛当中"
              });
            }
            database.collection('tb_item').where({
              matchid: that.data.matchid,
              index: 0 + ""
            }).get().then((g) => {

              that.setData({
                xuanshou: g.data
              });
              // 把选手数组当中的时间字段变成可以理解的内容
              for (let i = 0; i < that.data.xuanshou.length; i++) {
                var time = that.data.xuanshou[i].time;
                var d = time.toLocaleDateString().substring(0, 10);
                var t = time.toTimeString().substring(0, 8);
                var time = d + " " + t;
                that.data.xuanshou[i].time = time;
              }
              that.setData({
                xuanshou: that.data.xuanshou
              });
            });
            database.collection("tb_match").where({
              _id: that.data.matchid
            }).get().then((m) => {
              // 检查m.data[0]是否存在
              if (m.data && m.data[0]) {
                var imageList = m.data[0].imageList;
                var picnames = [];
                for (let i = 0 + ""; i < imageList.length; i++) {
                  var data = imageList[i];
                  var loc = data.lastIndexOf("/");
                  data = data.slice(loc + 1);
                  loc = data.lastIndexOf(".");
                  data = data.slice(0, loc);
                  picnames.push(data);
                }
                that.setData({
                  imageList: imageList,
                  picnames: picnames
                });
              } else {
                // 如果m.data[0]不存在，设置默认的imageList和picnames
                that.setData({
                  imageList: [],
                  picnames: []
                });
              }
              // 观察指定比赛、指定分项、指定用户的成绩是否存在
              database.collection("tb_item").where({
                userid: that.data.userid,
                matchid: that.data.matchid,
                index: 0 + ""
              }).get().then((a) => {
                if (a.data.length > 0) {
                  that.setData({
                    isWeiwancheng: false
                  });
                }
              });
            });
          },
          fail: err => {
            console.log(err);
          }
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})